import 'package:dio/dio.dart';
import 'package:fsharing/core/models/reg_new_qr.dart';
import 'package:fsharing/core/services/auth.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class RegNewModel extends ViewModel {
  final Auth auth;
  String _inviteCode = '';
  String username = '';
  String password = '';
  String passwordConfirm = '';
  String mobile = '';
  String checkCode = '';
  String _errorMessage;
  RegNewQr _data;

  RegNewModel(this.auth) : super();

  String get inviteCode => _inviteCode;

  set inviteCode(String value) {
    if (_inviteCode != value) {
      _inviteCode = value;
      notifyListeners();
    }
  }

  String get errorMessage => _errorMessage;

  RegNewQr get data => _data;

  /// 清除可选项
  void clearOptional() {
    username = '';
    password = '';
    passwordConfirm = '';
  }

  Future<ViewState> regNew() async {
    viewState = ViewState.busy;
    try {
      // if (inviteCode.isEmpty) {
      //   throw '请输入邀请码';
      // }
      if (mobile.isEmpty) {
        throw '请输入手机号';
      }
      if (checkCode.isEmpty) {
        throw '请输入验证码';
      }
      var params = <String, dynamic>{};
      params['checkCode'] = checkCode;
      params['inviteCode'] = inviteCode;
      params['mobile'] = mobile;
      params['password'] = password;
      params['password1'] = passwordConfirm;
      params['username'] = username;
      _data = await auth.regNew(params);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
